<script setup>
import { reactive, watch, ref } from 'vue';
import { useStudentStore } from '@/store/super-manger/studentStore';
import { storeToRefs } from 'pinia';
import { 
    submitFormApi, 
    updateBedNumberApi, 
    getStudentApi, 
    editStudentApi 
} from "@/service/student"
import { showElMessage } from '@/utils/showTipMessage'
// import router from '@/router/router';

const studentStore = useStudentStore();
const { 
    isShowStudentPanel, 
    panelTitle, 
    grades, 
    buildings, 
    room_names,
    bed_numbers,
    openPanelType,
    sno
 } = storeToRefs(studentStore);

const ruleFormRef = ref(null);
const form = reactive({
    sno: '',
    name: '',
    gender: '男',
    grade: '',
    class: '',
    building: '',
    room_name: '',
    bed_number: '',
    old_building: '',
    old_room_name: '',
    old_bed_number: '',
    telephone: '',
})

// 自定义校验规则
const rules = ref({
    sno: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    class: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    building: [{ required: true, message: '宿舍楼不能为空', trigger: 'change' }],
    room_name: [{ required: true, message: '宿舍号不能为空', trigger: 'change' }],
    bed_number: [{ required: true, message: '床位号不能为空', trigger: 'change' }],
    telephone: [{ required: true, message: '手机号不能为空', trigger: 'change' }],
});

// 监听面板是否被打开
watch(isShowStudentPanel, (newVal) => {
    if (newVal) {   // 面板被打开
         // 发送网络请求获取年级
         studentStore.getGradeInfo();
        if (openPanelType.value === 'edit') {
            // 根据学号请求学生信息
            handleStuInfo();
        }
    }
})
// 根据学号获取学生信息
async function handleStuInfo() {
    const res = await getStudentApi(null, sno.value);
    console.log(res.data)
    const { room_name, id } = res.data.data.room_name;
    const data = res.data.data;
    const keys = Object.keys(form);
    for (let key of keys) {
        if (key === 'bed_number') {
            form[key] = data[key].split('_')[1] + '号床';
            continue;
        }
        form[key] = data[key];
    }
    form["room_name"] = room_name;
    form.old_building = data.building;
    form.old_room_name = id;
    form.old_bed_number = data.bed_number;
    // 获取宿舍号和床位号
    if (form.building && form.room_name) {
        selectedBuilding(form.building);
        selectRoomName(id);
    }
}

// 选择性别后(根据性别显示对应的宿舍楼)
const selectedGender = (type) => {
    // 获取宿舍楼信息
    studentStore.getBuildingsData(type);
}

// 宿舍楼被选择后
const selectedBuilding = (buildingId) => {
    // 发送网络请求该宿舍楼的所有还有空余床位的宿舍号
    studentStore.getRoomName(buildingId)
}

// 宿舍号被选择后选择床位号
const selectRoomName = (dorId) => {
    studentStore.getBedNumber(dorId);
}

// 提交表单
const submitForm = async(formEl) => {
    if (!formEl) return;
    await formEl.validate( valid => {
        if (valid) {
            if (openPanelType.value === 'edit') {   // 编辑
                handleEditRequest();
                return;
            }
            handleAddRequest();
        }
    })
}
// 添加表单提交
async function handleAddRequest() {
    console.log(form)
    const res = await submitFormApi(form);
    const { code } = res.data;
    // 修改宿舍床位信息
    const type = 'add'; // 新增类型
    const res1 = await updateBedNumberApi(form.bed_number, form.room_name, type);
    if (code && res1.data.code) {   
        closePanel();   // 关闭面板
        showElMessage('学生信息添加成功！');
    }
}

// 编辑表单提交
async function handleEditRequest() {
    const res = await editStudentApi(form);
    const { code } = res.data;
    if (!code) {    // 表示编辑成功
        let room_name = '';
        // 1、修改床位号信息(编辑前、编辑后)
        await updateBedNumberApi(form.old_bed_number, form.old_room_name, 'edit');    // 编辑
        const result = String(form.room_name).startsWith('dor_');
        if (!result) {
            room_name = form.old_room_name;
        } else {
            room_name = form.room_name;
        }
        console.log(room_name);
        await updateBedNumberApi(form.bed_number, room_name, 'add'); // 新增
        // 2、显示提示信息，并刷新页面
        closePanel();
        showElMessage('编辑成功！');
    }
}

// 关闭面板
const closePanel = () => {
    isShowStudentPanel.value = false;
}

</script>

<template>
  <div class="student">
    <el-dialog 
        v-model="isShowStudentPanel" 
        :title="panelTitle"
        align-center
        :close-on-click-modal="false"
        width="400"
        :show-close="false"
    >
        <el-form 
            :model="form"
            ref="ruleFormRef"
            :rules="rules"
        >
            <el-form-item label="学生学号：" prop="sno">
                <el-input 
                    v-model="form.sno" 
                    placeholder="请输入学生学号"  
                    :disabled="openPanelType === 'edit'"
                />
            </el-form-item>
            <el-form-item label="学生姓名：" prop="name">
                <el-input v-model="form.name" placeholder="请输入学生姓名" />
            </el-form-item>
            <el-form-item label="性别：">
                <el-radio-group v-model="form.gender">
                    <el-radio label="男" @change="selectedGender('M')" />
                    <el-radio label="女"  @change="selectedGender('G')" />
                </el-radio-group>
            </el-form-item>
            <el-form-item label="学生年级：" prop="grade">
                <el-select v-model="form.grade" placeholder="请选择学生年级">
                    <template v-for="item of grades" :key="item">
                        <el-option :label="`${item} 级`" :value="item" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="学生班级" prop="class">
                <el-input v-model="form.class" placeholder="请输入学生班级" />
            </el-form-item>
            <el-form-item label="宿舍楼：" prop="building">
                <el-select 
                    v-model="form.building" 
                    placeholder="请选择宿舍楼"
                    @change="selectedBuilding(form.building)"
                >
                    <template v-for="item of buildings" :key="item.id">
                        <el-option :label="`${item.building_name} 号楼`" :value="item.building_name" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="宿舍号：" prop="room_name">
                <el-select 
                    v-model="form.room_name" 
                    placeholder="请选择宿舍号"
                    @change="selectRoomName(form.room_name)"
                >
                    <template v-for="item of room_names" :key="item.id">
                        <el-option :label="item.room_name" :value="item.id" />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="床位号：" prop="bed_number">
                <el-select 
                    v-model="form.bed_number" 
                    placeholder="请选择床位号"
                >
                    <template v-for="(item, index) of bed_numbers" :key="index">
                        <el-option 
                            v-if="!Number(item.value)" 
                            :label="`${index + 1}号床`" 
                            :value="item.key" 
                        />
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="手机号：" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入学生手机号" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button 
                    type="success" 
                    plain 
                    class="submitBtn" 
                    @click="submitForm(ruleFormRef)"
                >提交</el-button>
                <el-button @click="closePanel()">关闭</el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.el-form-item {
    margin: 0 auto;
    margin-bottom: 20px;
    width: 300px;
   
}
</style>